<template>
  <div class="wrap">
    <el-tabs v-model="activeName"  v-loading="loading">
      <el-tab-pane label="基地品质工程师配置" name="first">
        <el-form :model="tableForm" ref="formRef">
          <el-card>
            <el-table :data="tableForm.table" border :header-cell-style="{'text-align':'center'}"
                      :cell-style="{'text-align':'center'}">

              <el-table-column label="基地">
                <template slot-scope="scope">
                  <el-form-item label-width="0" :prop="`table.${scope.$index}.dept_name`"
                                :rules="{required: true, message: '基地必需', trigger: 'change'}">
                    <!--                  <el-autocomplete v-model="scope.row.dept_name" :fetch-suggestions="querySearchAsyncBase" class="w-full"-->
                    <!--                                   placeholder="请选择基地" value-key="nickname" @select="(val)=>handleSelectBase(val,scope.$index)">-->
                    <!--                    <template #default="{ item }">-->
                    <!--                      <div>{{ item.name }}</div>-->
                    <!--                      <el-divider/>-->
                    <!--                    </template>-->
                    <!--                  </el-autocomplete>-->
                    <el-select v-model="scope.row.dept_name" @change="(val)=>handleSelectBase(val,scope.$index)"
                               placeholder="请选择">
                      <el-option
                        clearable
                        :remote-method="remoteMethod"
                        v-for="item in baseOptions"
                        :key="item.id"
                        :label="item.name"
                        :loading="baseLoading"
                        :value="item"
                        :disabled="!!tableForm.table.find((val,itemIndex)  => val.dept_id == item.id && scope.$index !== itemIndex)"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="品质工程师">
                <template slot-scope="scope">
                  <el-form-item label-width="0" :prop="`table.${scope.$index}.user_name`"
                                :rules="{required: true, message: '品质工程师为必需', trigger: 'change'}">
                    <el-autocomplete v-model="scope.row.user_name" :fetch-suggestions="querySearchAsyncPerson"
                                     class="w-full"
                                     placeholder="请选择品质工程师" value-key="nickname"
                                     @select="(val)=>handleSelectPerson(val,scope.$index)">
                      <template #default="{ item }">
                        <div><b>{{ item.realname }}</b> &nbsp; &nbsp;&nbsp;部门: <span>{{ item.dept_name }}</span>
                          &nbsp;&nbsp;岗位:<span>{{ item.position_name }}</span></div>
                        <el-divider/>
                      </template>
                    </el-autocomplete>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="操作" fixed="right">
                <template slot-scope="scope">
                  <el-link type="danger" style="font-size: 18px" icon="el-icon-delete"
                           :disabled="tableForm.table.length<=1 "
                           @click="delList(scope.$index)"></el-link>
                </template>
              </el-table-column>
            </el-table>
            <div class="add-btn" @click="addList" style="margin-top: 5px"><i class="el-icon-plus"></i></div>
            <el-button type="primary" class="saveBtn" @click="save">保存更改</el-button>
          </el-card>
        </el-form>
      </el-tab-pane>
      <!--      <el-tab-pane label="配置管理" name="second">配置管理</el-tab-pane>-->
    </el-tabs>
  </div>
</template>

<script>
export default {
  name: "editTable",
  data() {
    return {
      fatherId: '',
      activeName: 'first',
      loading: false,
      baseOptions: [],
      baseLoading: false,
      valid: false,
      tableForm: {
        table: [
          {
            dept_id: '',
            user_id: '',
            dept_name: '',
            user_name: '',
          }
        ]
      },
    }
  },
  watch: {
    'tableForm.table': {
      handler(current) {
        this.$emit('change', current)
      },
      deep: true
    },
  },
  async mounted() {
    this.getData()

    new Promise(resolve => {
        this.getFatherId(resolve)
      }
    ).then(() => {
      this.remoteMethod()
    })

  },
  methods: {
    getFatherId(resolve) {
      this.$http.get(`/dept/index`).then((res) => {
        if (res.data.code === 0) {
          this.fatherId = res.data.data.filter((item) => {
            return item.name === '品质部'
          })[0].id
          resolve()
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //远程搜索基地
    remoteMethod(query) {
      if (query !== '') {
        this.baseLoading = true;
        this.$http.get(`/department/${this.fatherId}/all_child`).then((res) => {
          if (res.data.code === 0) {
            this.baseOptions = res.data.data
          } else {
            this.$message.error(res.data.msg);
          }
        });
      } else {
        this.options = [];
      }
      this.baseLoading = false;
    },
    //远程搜索人员
    querySearchAsyncPerson(query, cb) {
      query = query ? query : ''
      this.$http.get(`/user/index?limit=10&realname=${query} `).then((res) => {
        cb(res.data.data);
      });
    },

    getData() {
      this.loading = true;
      this.$http.get(`/settings`).then(res => {
        if (res.data.code === 0) {
          this.tableForm.table = res.data.data.pb_engineer.value || []
        }
        this.loading = false;
      });
    },
    /*选择基地*/
    handleSelectBase(val, index) {
      this.tableForm.table[index].dept_id = val.id
      this.tableForm.table[index].dept_name = val.name
    },
    /*选择品质工程师*/
    handleSelectPerson(val, index) {
      this.tableForm.table[index].user_id = val.id
      this.tableForm.table[index].user_name = val.realname
    },
    addList() {
      this.tableForm.table.push(
        {
          dept_id: '',
          user_id: '',
          dept_name: '',
          user_name: '',
        }
      )
    },
    delList(index) {
      this.$confirm("是否确认删除？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableForm.table.splice(index, 1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    save() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.loading = true;
          let pb_engineer = [...this.tableForm.table]
          this.$http.put(`/settings`, {pb_engineer}).then(res => {
            if (res.data.code === 0) {
              this.$message.success(res.data.msg)
            } else {
              this.$message.error(res.data.msg)
            }
            this.loading = false;
          });
        }
      })
    },
    validate() {
      this.$refs.formRef.validate(valid => {
        return this.valid = valid
      })
    },
  }

}
</script>

<style scoped lang="scss">
.el-table td div {
  margin: auto;
  box-sizing: border-box;
  width: 85%;
}

.wrap {
  margin: 20px;
}

.el-dialog:not(.ele-dialog-form) .el-dialog__body .el-form .el-form-item:last-child {
  margin-bottom: 0;
}

.add-btn {
  height: 57px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2px dashed var(--color-primary);
  //letter-spacing:1rem;
  i {
    font-size: 18px;
    color: var(--color-primary);
    font-weight: bolder;
  }

  &:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
    cursor: pointer;
  }

  &:active {
    color: var(--color-primary-7);
    border-color: var(--color-primary-7);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
  }
}

.saveBtn {
  margin-top: 20px;
}

</style>

